// ARDIEx1Client.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <string.h>
#include "SOCK_WrapperFacade.h"
#include "StopWatch.h"

#define DEFAULT_PORT 27016

int main(int argc, char* argv[])
{	
	unsigned long address = 0x7F000001;
	// Convert server address to hexadecimal base.
	if (argc > 1) {
		printf("Server set as %s\n", argv[1]);
		address = ntohl(inet_addr(argv[1]));
	} else
		printf("Server set as localhost\n");
	
	// On Windows start socket 2.2 system
	WSADATA wsa_data;
	WORD version_requested = MAKEWORD(2, 2);
	int error = WSAStartup(version_requested, &wsa_data);
	if (error != 0) return -1;

	INET_Addr addr(DEFAULT_PORT, address);
	SOCK_Connector *client; 
	SOCK_Stream *new_stream;
	StopWatch *stopWatch = new StopWatch();


	printf("Client creating connection\n");
		
	char message[500];
	char text[500];
    char tmpStr[100];

	if (argc > 1) {
		// Converts from unicode to string
		for (int i = 0; i < sizeof(text); i++)
			text[i] = (char)argv[1][i];
		sprintf_s(message, "Hello from Client: %s\n", text);
	} else
		sprintf_s(message, "Hello from Client\n");
		
	printf(message);

	for (int i = 0;i < 10000;i++)
	{
		// Sleep from 1s to 2s.
		//Sleep((double)rand() / RAND_MAX+1 * (2000 - 1000));

		client = new SOCK_Connector(addr);
		new_stream = new SOCK_Stream();

		sprintf_s(message, "Hello from Client %d\n", i);
		sprintf_s(tmpStr, "Client %d", i);

		stopWatch->start();
		client->connecting(*new_stream);
		if (new_stream->get_handle() != 0) {
			//printf("Client connected\n");
			new_stream->send_n(message, 100, 0);
			//Sleep(100); // Allow server to wakeup to receive message
			new_stream->recv_n(message, sizeof(message), 0);
		}
		stopWatch->split(tmpStr);
		stopWatch->stop();
		
		delete (new_stream);
		delete (client);
	}
	WSACleanup();
	return 0;
}

